package org.infoset.xml.memory;

import java.io.*;
import java.util.*;
import org.infoset.xml.*;
import org.infoset.xml.util.SiblingIterator;

public class MemoryCharacters extends MemoryTextDataItem implements Characters {

   int line;
   int column;
   int index;
   boolean cdataSection;

   public MemoryCharacters(Infoset infoset,Parent origin, String textValue, Object typedValue) {
      super(infoset,origin);
      setText(textValue);
      setTypedValue(typedValue);
      this.line = 0;
      this.column = 0;
      cdataSection = false;
   }
   
   public Item copyOfItem(boolean copyAll) {
      return new MemoryCharacters(infoset,null,value,data);
   }

   protected void setIndex(int index) {
      this.index = index;
   }

   public ItemType getType() {
      return ItemType.CharactersItem;
   }

   public Parent getParent() {
      return origin;
   }
   
   public Child getFollowingSibling() {
      return (Child)origin.get(index+1);
   }

   public Child getPrecedingSibling() {
      return (Child)origin.get(index-1);
   }
   
   public Object clone() {
      MemoryCharacters child = new MemoryCharacters(infoset,getParent(), value,data);
      child.setIndex(index);
      return child;
   }

   public Iterator getAxis(Infoset.Axis axis) {
      switch(axis) {
         case AncestorAxis:
            return new MemoryParent.AncestorIterator(this.getParent());
         case AncestorOrSelfAxis:
            return new MemoryParent.AncestorIterator(this);
         case PrecedingAxis:
            return new MemoryParent.PrecedingIterator(this);
         case FollowingAxis:
            return new MemoryParent.FollowingIterator(this);
         case PrecedingSiblingAxis:
            return new MemoryItem.PreviousSiblings(getPrecedingSibling());
         case FollowingSiblingAxis:
            return new MemoryItem.FollowingSiblings(getFollowingSibling());
         case DescendantOrSelfAxis:
            return Collections.singletonList(this).iterator();
         case SelfAxis:
            return Collections.singletonList(this).iterator();
         case ParentAxis:
            return Collections.singletonList(getParent()).iterator();
         default:
            return super.getAxis(axis);
      }
   }
   
   public Iterator getFollowingSiblings() {
      return new SiblingIterator(getFollowingSibling(),true);
   }
   
   public Iterator getPrecedingSiblings() {
      return new SiblingIterator(getPrecedingSibling(),false);
   }
   
   public int getColumn() {
      return column;
   }   

   public int getLine() {
      return line;
   }
   
   public void setColumn(int column) {
      this.column = column;
   }
   
   public void setLine(int line) {
      this.line = line;
   }
   
   public String toString() {
      return "[child '"+getText()+"' at "+index+"]";
   }
   
   public boolean isCDataSection() {
      return cdataSection;
   }
   
   public void setCDataSection(boolean flag) {
      cdataSection = flag;
   }
   
}
